
import ext from './extend.js';
function _getTron() {
	if (window.tronWeb) {
		return window.tronWeb;
	}
	return null;
}
//取得钱包地址
async function getWallet(obj) {
	//let obj = _getTron();
	//console.log(obj)
	if (obj === null) return {
		code: 0,
		msg: ext.lang('injectFail')
	}
	let address = obj.defaultAddress.base58 || ''
	return {
		code: 1,
		data: address
	}
}
//取得TRX余额
async function getBalance(obj) {
	let address = arguments[1] ? arguments[1] : '';
	//let obj = _getTron();
	if (obj === null) return {
		code: 0,
		msg: ext.lang('injectFail')
	}
	if (!obj.isAddress(address)) return {
		code: 0,
		msg: ext.lang('invalidAddress')
	}
	let balance = await obj.trx.getBalance(address);
	balance = await obj.fromSun(balance)
	return {
		code: 1,
		data: balance
	}
}
//取得TOKEN余额
async function getTokenBalance(obj) {
	let address = arguments[1] ? arguments[1] : '';
	let contract_addres = arguments[2] ? arguments[2] : 'TXa9L8vmA3qvMcCbCbxSDz5JAN3bZg9kdZ';
	//let obj = _getTron();
	if (obj === null) return {
		code: 0,
		msg: ext.lang('injectFail')
	}
	if (!obj.isAddress(address)) return {
		code: 0,
		msg: ext.lang('invalidAddress')
	}
	if (!obj.isAddress(contract_addres)) return {
		code: 0,
		msg: ext.lang('invalidContractAddres')
	}
	let contract = await obj.contract().at(contract_addres);
	let result = await contract.balanceOf(address).call();
	let balance = await obj.toDecimal(result._hex) / Math.pow(10, 8);
	return {
		code: 1,
		data: balance
	}
}
//TRX转账
async function transferTrx(obj,data) {
	//let obj = _getTron();
	if (obj === null) return {
		code: 0,
		msg: ext.lang('injectFail')
	}
	let _from = data.from || me.address;
	let _to = data.to;
	let _amount = amount = data.amount;
	if (!obj.isAddress(_from)) return {
		code: 0,
		msg: ext.lang('invalidFromAddres')
	}
	if (!obj.isAddress(_to)) return {
		code: 0,
		msg: ext.lang('invalidToAddres')
	}
	let balance = await getBalance(obj,_from);
	if (balance < _amount) return {
		code: 0,
		msg: ext.lang('trxAmountNotEnough'),
		err: ''
	}
	_amount = await obj.toSun(_amount)
	try {
		var tx = await obj.transactionBuilder.sendTrx(_to, _amount, _from);
	} catch (e) {
		return {
			code: 0,
			msg: ext.lang('transactionSendFail'),
			err: e
		}
	}
	try {
		var signedTx = await obj.trx.sign(tx);
	} catch (e) {
		return {
			code: 0,
			msg: ext.lang('transactionSignFail'),
			err: e
		}
	}
	try {
		var broastTx = await obj.trx.sendRawTransaction(signedTx);
	} catch (e) {
		return {
			code: 0,
			msg: ext.lang('transactionBroastFail'),
			err: e
		}
	}
	var result = broastTx.result || false;
	var txId = broastTx.txid || ''
	if (!result) return {
		code: 0,
		msg: ext.lang('transactionBroastFail'),
		err: ''
	}
	return {
		code: 1,
		txId: txId,
		from: _from,
		to: _to,
		amount: amount
	}
}
//SFB转账
async function transferSfb(obj,data) {
	//let obj = _getTron();
	if (obj === null) return {
		code: 0,
		msg: ext.lang('injectFail')
	}
	let _from = data.from || me.address;
	let _to = data.to;
	let _amount = amount = data.amount;
	let _contractAddress = data.contract || 'TXa9L8vmA3qvMcCbCbxSDz5JAN3bZg9kdZ';
	if (!obj.isAddress(_from)) return {
		code: 0,
		msg: ext.lang('invalidFromAddres')
	}
	if (!obj.isAddress(_to)) return {
		code: 0,
		msg: ext.lang('invalidToAddres')
	}
	let balanceTRX = await getBalance(obj,_from);
	let balance = await getTokenBalance(obj,_from);
	if (balanceTRX < 6) return {
		code: 0,
		msg: ext.lang('trxAmountNotEnough')
	}
	if (balance < _amount) return {
		code: 0,
		msg: ext.lang('sfbAmountNotEnough'),
		err: ''
	}
	_amount = await obj.toHex(_amount * Math.pow(10, 8))
	try {
		let contract = await obj.contract().at(_contractAddress);
		let result = await contract.transfer(_to, _amount).send({
			feeLimit: 10000000
		}).then(txId => {
			return {
				code: 1,
				txId: txId,
				from: _from,
				to: _to,
				amount: amount
			}
		});
	} catch (e) {
		return {
			code: 0,
			msg: ext.lang('transactionSFBFail'),
			err: e
		}
	}
}
//添加指定代币
async function wakeToken(obj) {
	let contract = arguments[1] ? arguments[1] : 'TXa9L8vmA3qvMcCbCbxSDz5JAN3bZg9kdZ';
	//let obj = _getTron();
	if (obj === null) return {
		code: 0,
		msg: ext.lang('injectFail')
	}
	let tx = await obj.request({
		method: 'wallet_watchAsset',
		params: {
			type: 'trc20',
			options: {
				address: contract
			},
		},
	});
	return {
		code:1,
		data:tx
	}
}
//钱包事件监控
function WalletEventHook(cb){
	window.addEventListener('message', function(e) {
		if (e.data.message && e.data.message.action == "setAccount") {
			//me.address = e.data.message.data.address
			cb && cb({event:'tagAddress',data:e.data.message.data.address})			
		}
		if (e.data.message && e.data.message.action == "setNode") {
			let node = e.data.message.data.node.eventServer;
			if (node == 'https://api.trongrid.io' || node == 'https://api.tronstack.io') {
				//me.network = 'main';
				cb && cb({event:'tagNetwork',data:'main'})
			} else {				
				//me.network = 'test';
				cb && cb({event:'tagNetwork',data:'test'})
			}
		}
		if (e.data.message && e.data.message.action == "tabReply") {
			
		}
	});
}

module.exports = {    
	getTron:_getTron,
	getWallet,
	getBalance,
	getTokenBalance,
	transferTrx,
	transferSfb,
	wakeToken,
	WalletEventHook	
}